package org.phonetic.aspect;

import java.util.List;

import javax.persistence.EntityManager;

import org.application.bean.PacienteDao;
import org.application.model.Paciente;
import org.phonetic.model.PacientePhoneticCode;

public aspect PhoneticDelete {

	declare warning : execution( void PacienteDao.delete(..)) :
		"A implementação deste método foi alterada pelo aspecto org.phonetic.aspect.PhoneticDelete";

	pointcut executeDelete(Paciente paciente, PacienteDao dao) 
	: execution( void PacienteDao.delete(Paciente)) && args(paciente) && target(dao);

	void around(Paciente paciente, PacienteDao dao) : executeDelete(paciente, dao){
		EntityManager entityManager = dao.getEntityManager();
		String query = "SELECT ppc FROM PacientePhoneticCode ppc WHERE ppc.paciente.id = :id";
		@SuppressWarnings("unchecked")
		List<PacientePhoneticCode> codes = entityManager.createQuery(query)
				.setParameter("id", paciente.getId()).getResultList();
		for (PacientePhoneticCode code : codes) {
			entityManager.remove(code);
		}
		proceed(paciente, dao);
	}
}
